﻿package 
{
	import flash.display.Sprite;  
	import flash.display.MovieClip;  
	import flash.net.URLLoader;  
	import flash.net.URLRequest;  
	import flash.display.Loader;  
	import flash.events.Event;  
	import flash.filters.BitmapFilter;  
	import flash.filters.DropShadowFilter;  
	import flash.text.TextFormat;  
	import flash.text.TextField;  
	import flash.text.AntiAliasType;  
	import flash.events.MouseEvent;  
	import fl.transitions.Tween;  
	import fl.transitions.easing.*; 
	import fl.transitions.TweenEvent;  
	import flash.display.MovieClip
	import fl.containers.ScrollPane;
	import fl.containers.BaseScrollPane;
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.*;
	import flash.net.*;
	
	public class Main extends MovieClip
	{
			
		//Customizable Variables
		var fadeSpeed:Number;
		var moveSpeed:Number;
		var scrollSpeed:Number;
		var backgroundImage:String;
		var headerText:String;
		var footerText:String;
		var maxVisibleButtons:int = 8;		
		var myTextFormat:TextFormat;
		
		//Required Variables
		var preloader:Preloader = new Preloader();
		var MainMenuPane:ScrollPane = new ScrollPane();
		var MainPaneSrc:MovieClip = new MovieClip();
		var ContentPane:ScrollPane = new ScrollPane();
		var ContentSrc:MovieClip = new MovieClip();
		
		var myXML:XML;		
		var myXMLList:XMLList;
		var parentList:Array = new Array();	
		var currentbuttons = new Array();
		var incomingbuttons = new Array();		
		
		var tweenVar:int = 1;
		var xTween:Tween;
		var alphaTween:Tween;		
		var upTween:Tween;
		var downTween:Tween;
		var backTween:Tween;	
				
		var up:UpArrow;
		var down:DownArrow;
		var back:BackArrow;
		var backBool:Boolean = false;
		var scrollAmount:int;
		
		
		
		public function Main(): void
		{	
			//stage.scaleMode = "noScale";
			stage.displayState = StageDisplayState.FULL_SCREEN;
			stage.stageHeight = 700;
			stage.stageWidth = 1280;
			
			trace(stage.height + "  " + stage.width);
			removeChild(INFO);
			LoadOptions("main.xml");
			LoadPanes();
			LoadXML("main.xml");		
			
		}		
		public function LoadOptions(file:String)
		{
			var urlLoader:URLLoader = new URLLoader();
			var urlReq:URLRequest = new URLRequest(file);
			urlLoader.load(urlReq);
			urlLoader.addEventListener(Event.COMPLETE, parseOptions );
		}
		public function parseOptions(e:Event)
		{
			var tempxml:XML = new XML(e.target.data);
			tempxml.ignoreWhitespace = true;
			tempxml.ignoreComments = true;			
			
			myTextFormat = new TextFormat(
								tempxml.CustomizableSettings[0].MainMenuFont[0].TextFont[0].@TextFont, 		
								tempxml.CustomizableSettings[0].MainMenuFont[0].FontSize[0].@FontSize,		
								tempxml.CustomizableSettings[0].MainMenuFont[0].FontColor[0].@FontColor,	
								tempxml.CustomizableSettings[0].MainMenuFont[0].Bold[0].@BoldFont,			
								tempxml.CustomizableSettings[0].MainMenuFont[0].Italic[0].@ItalicFont, 		
								tempxml.CustomizableSettings[0].MainMenuFont[0].Underlined[0].@UnderlinedFont, 		
								null,
								null,
								tempxml.CustomizableSettings[0].MainMenuFont[0].Alignment[0].@Aligned,
								tempxml.CustomizableSettings[0].MainMenuFont[0].LeftMargin[0].@Space,
								tempxml.CustomizableSettings[0].MainMenuFont[0].RightMargin[0].@Space, 
								false,		
								0				
								);
			
			fadeSpeed = tempxml.CustomizableSettings[0].Transitions[0].FadeSpeed[0].@Speed ;
			moveSpeed = tempxml.CustomizableSettings[0].Transitions[0].MoveSpeed[0].@Speed ;
			scrollSpeed = tempxml.CustomizableSettings[0].Transitions[0].ScrollSpeed[0].@Speed ;
			headerText = tempxml.CustomizableSettings[0].Background[0].Header[0];
			footerText = tempxml.CustomizableSettings[0].Background[0].Footer[0];
			
			backgroundImage = tempxml.CustomizableSettings[0].Background[0].BackgroundImage[0].@Image;
			LoadBackground(backgroundImage);			
		}	
		public function testFunction(e:Event)
		{			
			MainMenuPane.blendMode = "screen";
			MainMenuPane.refreshPane();
		}
		public function LoadPanes():void
		{
			MainMenuPane.blendMode = "screen";
			MainMenuPane.source = MainPaneSrc;
			MainMenuPane.setSize(200,600);
			MainMenuPane.verticalScrollPolicy = "off";
			MainMenuPane.horizontalScrollPolicy = "off";
			MainMenuPane.x = 50;
			MainMenuPane.y = 200;
			
			ContentPane.blendMode = "screen";
			ContentPane.source = ContentSrc;
			ContentPane.setSize(800,500); 	
			ContentPane.verticalScrollPolicy = "off";
			ContentPane.horizontalScrollPolicy = "off";
			ContentPane.x = 400;
			ContentPane.y = 100;			
		}
		public function LoadBackground(file:String):void
		{
			var loader = new Loader();			
			var backrequest = new URLRequest(file);			
			loader.load(backrequest);
			loader.contentLoaderInfo.addEventListener(Event.COMPLETE, AddBackground);
		}
		public function AddBackground(e:Event):void
		{
			var templateBitmap:Bitmap = e.target.content;
   			var templateBitmapData:BitmapData = templateBitmap.bitmapData;
			var imageBitmap:Bitmap = new Bitmap(templateBitmapData);
			
			trace(stage.width);
			
			imageBitmap.smoothing = true;
			addChildAt(imageBitmap, 0);
			
			/*if (imageBitmap.width > stage.width || imageBitmap.height > stage.height)
			{
				trace("scaling");
				if (imageBitmap.width <= imageBitmap.height ) {
					imageBitmap.scaleX = (stage.width) / imageBitmap.width ;
					imageBitmap.scaleY = (stage.width) / imageBitmap.width;
				}
				else { 
					imageBitmap.scaleX = (stage.height) / imageBitmap.height; 
					imageBitmap.scaleY = (stage.height) / imageBitmap.height; 
				}	
				addChildAt(imageBitmap, 0);
				imageBitmap.x = (stage.width - imageBitmap.width) / 2 ;
				imageBitmap.y = (stage.height - imageBitmap.height) / 2 ;																			  
			}
			else 
			{
				addChildAt(imageBitmap, 0);
				imageBitmap.x = 0 ;
				imageBitmap.y = 0 ;	
			}*/
			
			
			
			
			
			
		}
		

		public function LoadXML(file:String)
		{
			var urlLoader:URLLoader = new URLLoader();
			var urlReq:URLRequest = new URLRequest(file);
			urlLoader.load(urlReq);
			urlLoader.addEventListener(Event.COMPLETE, parseMenu );
		}		
		public function parseMenu(e:Event)
		{
			var xml:XML = new XML(e.target.data);	
			xml.ignoreComments = true;
			xml.ignoreWhitespace = true;
			
			myXML = xml.Spacer[0];			
			myXMLList = myXML..MainButton;
			
			var nodelist:XMLList = myXMLList.(attribute("Name") == "Main Menu");
			makeMenu(nodelist);
			
			addChild(MainMenuPane);
			addChild(ContentPane);
		}
		public function checkForSubMenu(s:String):Boolean
		{
			var nlist:XMLList = myXMLList.(attribute("Name") == s);
			if (nlist.MainButton.length() > 0 ) {  return true; }
			else { return false; }
		}		
		public function checkForContent(menuXML:*, i:int):Boolean
		{
			var s:String = menuXML.MainButton[i].@Content;
			if (s == "") {return false;}
			else { return true;}
		}
		public function makeMenu(menuXML:* ):void 
		{
			var mc:MovieClip = new MovieClip();
			var tempheight:int = 0;
			
			var tempsub:Boolean = false;
			var tempcontent:Boolean = false;
			
			if (menuXML.MainButton.length() > 0)
			{				
				for (var i:int = 0; i < menuXML.MainButton.length(); i++)
				{	
					tempsub = checkForSubMenu(menuXML.MainButton[i].@Name); 
					tempcontent = checkForContent(menuXML, i);				
					var a:MainButton = new MainButton(menuXML.MainButton[i].@Name,myTextFormat, tempsub, tempcontent, menuXML.MainButton[i].@Content);
					mc.addChild(a);
					a.y = ((a.h) * i) ;
					
					incomingbuttons.push(a);
					tempheight = a.h;
				}
				if ( checkButtons() ) { incomingbuttons.splice(0,incomingbuttons.length);}
				else if (!checkButtons()) 
				{						
						removeCurrentListeners();
						
						var target:int;
						var incoming:int;
						if (tweenVar == 1) {target = 200; incoming = -200;}
						if (tweenVar == 0) {target = -200; incoming = 200;}					
						try {
							xTween = new Tween(MainPaneSrc.getChildAt(0), "x", Regular.easeInOut, 0, target, moveSpeed, true);
							xTween.addEventListener(TweenEvent.MOTION_FINISH, removeMC);
						}
						catch(errObject:Error) { /* since there is not content on first load */ }
						tweenVar = 1;						
											
						handleBack();
						MainPaneSrc.addChild(mc);
						xTween = new Tween(mc, "x", Regular.easeInOut, incoming, 0, moveSpeed, true);
						xTween.addEventListener(TweenEvent.MOTION_FINISH, addNewListeners);						
												
						//Refresh Main Pane
						MainMenuPane.source = MainPaneSrc;
						MainMenuPane.setSize(200, maxVisibleButtons * tempheight);
						
						if (mc.height > maxVisibleButtons * tempheight) addScrollButtons();
						else if (mc.height <= maxVisibleButtons * tempheight) 
						{
							try {
								upTween = new Tween(up, "alpha", Regular.easeInOut, 1, 0, fadeSpeed, true);
								downTween = new Tween(down, "alpha", Regular.easeInOut, 1, 0, fadeSpeed, true);
								downTween.addEventListener(TweenEvent.MOTION_FINISH, removeScrollButtons);
							}
							catch (errObject:Error) { }			
						}										
				}			
				
			}		
			tweenVar = 1;
			scrollAmount = tempheight;
		}
		public function removeCurrentListeners():void
		{
			trace("listeners removed");
			try {	back.removeEventListener(MouseEvent.CLICK, backArrowPressed); }
			catch(errObject:Error) {}
			
			for each (var j in currentbuttons) {
					j.removeEventListener(MouseEvent.CLICK, buttonClick);
					j.removeListeners();
					
					try { j.removeEventListener(MouseEvent.CLICK, subMenuLoad); }
					catch (errObject:Error) {}
					
					try { j.removeEventListener(MouseEvent.CLICK, contentLoad); }
					catch (errObject:Error) {}
			}
		}
		public function addNewListeners(e:Event):void
		{
			moveButtons();
					
			try {	back.addEventListener(MouseEvent.CLICK, backArrowPressed); }
			catch(errObject:Error) {}
			
			for each (var j in currentbuttons) {
				j.addEventListener(MouseEvent.CLICK, buttonClick);
				if (j.hasSub == true) j.addEventListener(MouseEvent.CLICK, subMenuLoad);
				if (j.hasContent == true) j.addEventListener(MouseEvent.CLICK, contentLoad);
				j.addListeners();
			}			
		}
		public function addScrollButtons():void
		{
			up = new UpArrow();
			addChild(up);
			up.x = MainMenuPane.x + 25;
			up.y = MainMenuPane.y + MainMenuPane.height + 5;
			
			upTween = new Tween(up, "alpha", Regular.easeInOut, 0, 1,fadeSpeed, true);
			upTween.addEventListener(TweenEvent.MOTION_FINISH, upArrowReset);
						
			down = new DownArrow();
			addChild(down);
			down.x = MainMenuPane.x + 70;
			down.y = MainMenuPane.y + MainMenuPane.height + 5;
			
			downTween = new Tween(down, "alpha", Regular.easeInOut, 0, 1, fadeSpeed, true);
			downTween.addEventListener(TweenEvent.MOTION_FINISH, downArrowReset);
		}
		public function removeScrollButtons(e:Event):void
		{
			try { removeChild(up);removeChild(down);}
			catch (errObject:Error) {}
		}
		public function downArrowPressed(e:Event):void
		{
			down.removeEventListener(MouseEvent.CLICK, downArrowPressed);
			downTween = new Tween(MainMenuPane.verticalScrollBar,"scrollPosition", Regular.easeInOut, MainMenuPane.verticalScrollBar.scrollPosition, 
							   MainMenuPane.verticalScrollBar.scrollPosition += scrollAmount, .5, true);
			downTween.addEventListener(TweenEvent.MOTION_FINISH, downArrowReset);			
		}
		public function downArrowReset(e:Event):void
		{
			down.addEventListener(MouseEvent.CLICK, downArrowPressed);
			downTween.removeEventListener(TweenEvent.MOTION_FINISH, downArrowReset);	
		}
		public function upArrowPressed(e:Event):void
		{
			up.removeEventListener(MouseEvent.CLICK, downArrowPressed);
			upTween = new Tween(MainMenuPane.verticalScrollBar,"scrollPosition",Regular.easeInOut, MainMenuPane.verticalScrollBar.scrollPosition, 
							   MainMenuPane.verticalScrollBar.scrollPosition -= scrollAmount,.5, true);
			upTween.addEventListener(TweenEvent.MOTION_FINISH, upArrowReset);			
		}
		public function upArrowReset(e:Event):void
		{
			up.addEventListener(MouseEvent.CLICK, upArrowPressed);
			upTween.removeEventListener(TweenEvent.MOTION_FINISH, upArrowReset);	
		}
		public function handleBack():void
		{
			if (parentList.length > 0 ) 
				{
					if (backBool == false) 
					{					
						back = new BackArrow(parentList[parentList.length - 1]);
						trace("added back");
						addChild(back);
						back.x = MainMenuPane.x - 40;
						back.y = MainMenuPane.y;
						backTween = new Tween(back, "alpha", Regular.easeInOut, 0, 1, fadeSpeed, true);
						backBool = true;
					}					
				}
				else if (parentList.length <= 0 )
				{
					try { 
						back.removeEventListener(MouseEvent.CLICK, backArrowPressed);
						backTween = new Tween(back, "alpha", Regular.easeInOut, 1, 0, fadeSpeed, true);
						backTween.addEventListener(TweenEvent.MOTION_FINISH, removeBack);
						
					}
					catch (errObject:Error) { }		
					backBool = false;
				}
		}
		public function removeBack(e:Event):void
		{
			try { 
				removeChild(back);
				backTween.removeEventListener(TweenEvent.MOTION_FINISH, removeBack);
			}
			catch (errObject:Error) {}
		}
		public function checkButtons():Boolean
		{
			var i:int = 0;
			
			if (incomingbuttons.length != currentbuttons.length) {  return false; }
			else {
				for each (var b in incomingbuttons) {
					
					if ( b.buttonName != currentbuttons[i].buttonName ) {  return false; }
					else  { i++ }
				}
				return true;					
			}
		}
		public function moveButtons():void
		{
			//move incoming buttons to current array
			currentbuttons.splice(0, currentbuttons.length);
			currentbuttons = incomingbuttons.splice(0,incomingbuttons.length);
		}
		public function removeMC(e:Event):void
		{
			try {
				MainPaneSrc.removeChildAt(0);
			}
			catch(errObject:Error) { /* since there is no content on first load */ }
			
		}
		public function buttonClick(e:Event)
		{
			for each (var a in currentbuttons) {
				if (e.target.parent.buttonName == a.buttonName) {}
				else a.resetColorTween(); 
			}
		}
		public function subMenuLoad(e:Event)
		{
			var nodelist:XMLList = myXMLList.(attribute("Name") == e.target.parent.buttonName);
			var a:String = myXMLList.(attribute("Name") == e.target.parent.buttonName).parent().@Name;
			parentList.push(a);
			trace(parentList);
			makeMenu(nodelist);
		}
		public function backArrowPressed(e:Event):void
		{
			back.removeEventListener(MouseEvent.CLICK, backArrowPressed);
			tweenVar = 0;
			var nodelist:XMLList = myXMLList.(attribute("Name") == parentList[parentList.length - 1] );
			parentList.pop();
			makeMenu(nodelist);
		}
		public function contentLoad(e:Event)
		{
			try { ContentSrc.removeChildAt(0); }
			catch (errObject:Error) {}				
		}
		
	}
}
